package fr.umlv.graph;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ListGraph implements Graph{

	private final List<Edge>[] graph;
	private final int sommet;
	private int nbEdges;
	
	@SuppressWarnings("unchecked")
	public ListGraph(int vertex){
		if(vertex <= 0)
			throw new IllegalArgumentException();
		this.sommet = vertex;
		this.graph = new List[sommet];
	}
	
	@Override
	public int nombreSommets() {
		return this.sommet;
	}

	@Override
	public int nombreArcs() {
		return nbEdges;
	}

	@Override
	public boolean existeArc(Edge a) {
		if(nombreArcs() == 0)
			return false;
		if(graph[a.getStart()] == null || graph[a.getStart()].isEmpty())
			return false;
		return graph[a.getStart()].contains(a.getEnd());
	}

	@Override
	public void ajouterArc(Edge a) {
		if(graph[a.getStart()] == null)
			graph[a.getStart()] = new ArrayList<>();
		((List<Edge>)graph[a.getStart()]).add(a);
	}

	@Override
	public void supprimerArc(Edge a) {
		if(!existeArc(a))
			return;
		graph[a.getStart()].remove(a);
	}

	public String toStringDot() {
		StringBuilder sb = new StringBuilder("ListGraph {\n");
		for (List<Edge> edge : graph)
			if(edge!=null)
				for (Edge e : edge) 
					sb.append(e.toStringDot()).append('\n');
		sb.append('}');
		return sb.toString();
	}

	@Override
	public String toString() {
		return "ListGraph [graph=" + Arrays.toString(graph) + "]";
	}	
}
